const PubSub = {}

let callbacksObj = {}

let id = 0

PubSub.subscribe = function (msgName, callback) {
  var uuid = ++id
  var callbacks = callbacksObj[msgName]
  if (callbacks) {
    callbacks[uuid] = callback
  } else {
    callbacksObj[msgName] = {
      [uuid]: callback
    }
  }
  return uuid
}

PubSub.publish = function (eventName, data) {
  var callbacks = callbacksObj[eventName]
  if (callbacks) {
    Object.keys(callbacks).forEach((key) => {
      callbacks[key](data)
    })
  }
}

PubSub.unSubscribe = function (flag) {
  if (flag === undefined) {
    callbacksObj = {}
  }

  if (callbacksObj[flag]) {
    delete callbacksObj[flag]
  } else {
    var index = Object.values(callbacksObj).findIndex((obj) => Object.keys(obj).includes(flag))
    if (index > -1) {
      var target = Object.values(callbacksObj)[index]
      delete target[flag]
    }
  }
}

export default PubSub
